package cn.com.mma.mobile.tracking.api;

import cn.com.mma.mobile.tracking.util.Logger;
import cn.com.mma.mobile.tracking.util.SharedPreferencedUtil;
import android.content.Context;
import android.content.SharedPreferences;

/**
 * 发送事件
 * 
 * @author lincoln
 * 
 */
public class SendEventMessage {
	private static SendMessageThread normalThread, failedThread;
	private static Context context;
	/**
	 * 单例模式 Begin
	 */
	private static SendEventMessage sendEventMessage = new SendEventMessage();

	public static SendEventMessage getSendEventMessage(Context mContext) {
		context = mContext;
		return sendEventMessage;
	}

	private SendEventMessage() {
	}

	/**
	 * 单例模式 End
	 */

	/**
	 * 发送消息相关方法 Begin
	 */
	/**
	 * send normal message
	 */
	public void sendNromalList() {
		Logger.d("thread_sendNormalList");

		if (normalThread != null && (normalThread.getState() == Thread.State.NEW || normalThread.isAlive())) {
			return;
		}
		SharedPreferences sp = SharedPreferencedUtil.getSharedPreferences(context, SharedPreferencedUtil.SP_NAME_NORMAL);
		if (sp == null || sp.getAll().isEmpty())
			return;
		normalThread = new SendMessageThread(SharedPreferencedUtil.SP_NAME_NORMAL, context, true);
		normalThread.start();

	}

	/**
	 * send error message
	 */
	public void sendFailedList() {
		if (failedThread != null && (failedThread.getState() == Thread.State.NEW || failedThread.isAlive())) {
			return;
		}
		SharedPreferences sp = SharedPreferencedUtil.getSharedPreferences(context, SharedPreferencedUtil.SP_NAME_FAILED);
		if (sp == null || sp.getAll().isEmpty())
			return;
		failedThread = new SendMessageThread(SharedPreferencedUtil.SP_NAME_FAILED, context, false);
		failedThread.start();

	}

	/**
	 * stop send
	 */
	public void stopThread() {
		if (SendEventMessage.normalThread != null && SendEventMessage.normalThread.isAlive())
			SendEventMessage.normalThread.interrupt();
		if (SendEventMessage.failedThread != null && SendEventMessage.failedThread.isAlive())
			SendEventMessage.failedThread.interrupt();
	}

	/**
	 * clear all Data
	 */
	public void clearAll() {
		stopThread();
		SharedPreferencedUtil.clearAllDataInSP(context, SharedPreferencedUtil.SP_NAME_NORMAL);
		SharedPreferencedUtil.clearAllDataInSP(context, SharedPreferencedUtil.SP_NAME_FAILED);
		SharedPreferencedUtil.clearAllDataInSP(context, SharedPreferencedUtil.SP_NAME_OTHER);
	}

	/**
	 * clear error Data
	 */
	public void clearErrorList() {
		SharedPreferencedUtil.clearAllDataInSP(context, SharedPreferencedUtil.SP_NAME_FAILED);
	}

	/**
	 * 发送消息相关方法 End
	 */
}
